<template>
    <view class="x-sign-container">
        <canvas class="x-sign-canvas" :canvas-id="canvasId" :id="canvasId" :style="canvasStyle"
            @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd"></canvas>
        <view class="x-sign-actions">
            <button @click="handleReset">重置</button>
            <button @click="handleExportImg">导出图片到相册</button>
            <button @click="handleExportBase64">导出Base64</button>
        </view>
        <image :src="imgSrc"></image>
    </view>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
declare const uni: any

const imgSrc = ref("")

const emits = defineEmits(['reset', 'export-img', 'export-base64'])
const props = defineProps({
    width: { type: Number, default: 300 },
    height: { type: Number, default: 150 },
    lineWidth: { type: Number, default: 1 },
    lineColor: { type: String, default: '#f00' }
})

const canvasId = 'x-sign-canvas'
const canvasStyle = `width: ${props.width}px; height: ${props.height}px; border: 1px solid #ccc; background: #fff;`
const isDrawing = ref(false)
const lastPoint = ref<{ x: number, y: number } | null>(null)
let ctx: any = null
let rect: any = null

import { getCurrentInstance } from 'vue';
const instance: any = getCurrentInstance();
console.log('instance', instance);


onMounted(() => {

    nextTick(() => {

        ctx = uni.createCanvasContext(canvasId)
        console.log("🚀 ~ nextTick ~ ctx:", ctx)
        ctx.setLineWidth(props.lineWidth)
        ctx.setStrokeStyle(props.lineColor)

        const query = uni.createSelectorQuery().in(instance.proxy);
        query
            .select("#" + canvasId)
            .boundingClientRect((data) => {
                console.log("得到布局位置信息" + JSON.stringify(data));
                console.log("节点离页面顶部的距离为" + data.top);
                rect = data
            })
            .exec();
    })
})

function getPoint(e: any) {
    // console.log('eeee', e)
    const { x, y } = e.changedTouches[0]
    return {
        x: x,
        y: y
    }
}

function onTouchStart(e: any) {
    isDrawing.value = true
    ctx.beginPath()
    lastPoint.value = getPoint(e)
    console.log('lastPoint.value', lastPoint.value)

}
function onTouchMove(e: any) {
    if (!isDrawing.value) return
    const point = getPoint(e)
    drawLine(lastPoint.value, point)
    lastPoint.value = point
}
function onTouchEnd(e: any) {
    isDrawing.value = false
    lastPoint.value = null
}

function drawLine(from: any, to: any) {
    // debugger


    if (!ctx || !from || !to) return

    // console.log('from to', from, to);


    ctx.moveTo(from.x, from.y)
    ctx.lineTo(to.x, to.y)
    ctx.stroke()
    ctx.draw(true)
}
function handleReset() {
    // debugger
    if (!ctx) return
    ctx.clearRect(0, 0, props.width, props.height)
    ctx.draw()
    emits('reset')
}
function handleExportImg() {
    uni.canvasToTempFilePath({
        canvasId,
        success: (res) => {
            console.log('save res', res)
            // 1。这里已经导出到临时路径。有了临时路径就已经可以通过 uni.uploadFile 上传文件到服务器了
            // uploadFile 里通过filePath 指定路径上传。这个路径可以是上面的 tempPath
            // 可以进一步通过 uploadTask 管控上传行为

            // // 2。这里是已经存到本地的相册了
            // uni.saveImageToPhotosAlbum({
            //     filePath: res.tempFilePath,
            //     success: () => {
            //         uni.showToast({
            //             title: '图片保存成功',
            //             icon: 'success'
            //         });


            //         // setTimeout(() => {
            //         //     // 可以通过 tempFilePath 在页面里预览导出的图
            //         //     // 这样form-item 的签名展示区域，就可以展示这个 tempFilePath
            //         //     imgSrc.value = res.tempFilePath
            //         // }, 1000);

            //         // setTimeout(() => {
            //         //     uni.previewImage({
            //         //         urls: [res.tempFilePath],
            //         //         showmenu: false
            //         //     })
            //         // }, 1000)
            //     },
            //     fail: (err) => {
            //         console.error('保存图片失败：', err);
            //         uni.showToast({
            //             title: '保存图片失败',
            //             icon: 'none'
            //         });
            //     }
            // });

            // 3、 拿 fileInfo 试试
            uni.getFileInfo({
                filePath: res.tempFilePath,
                success: (result) => {
                    console.log("🚀 ~ handleExportImg ~ result:", result)
                    uni.showToast({
                        title: "getFileInfo 成功",
                        icon: 'none'
                    })

                },
                fail: (error) => {
                    console.log("🚀 ~ handleExportImg ~ error:", error)


                }
            })
        },
        fail: (err) => {
            console.log('保存图片失败：', err);
        }
    }, uni)
}
function handleExportBase64() {

    uni.canvasToTempFilePath({
        canvasId,
        success: (res) => {
            // 读取文件转base64
            // App端
            // #ifdef APP-PLUS
            console.log('canvasToTempFilePath res', res);

            plus.io.resolveLocalFileSystemURL(res.tempFilePath, function (entry) {
                entry.file(function (file) {
                    console.log('====file', file);

                    const fileReader = new plus.io.FileReader();
                    fileReader.onloadend = function (evt) {
                        // evt.target.result 形如 data:application/octet-stream;base64,xxxx
                        // 你可以直接用 evt.target.result
                        console.log('66666', evt);

                        emits('export-base64', evt.target.result);
                    };
                    fileReader.readAsDataURL(file);
                });
            });
            // #endif
        }
    }, uni)
}
</script>

<style scoped>
.x-sign-canvas {
    border: 1px solid #ccc;
    background: #fff;
    touch-action: none;
}

.x-sign-actions {
    margin-top: 10px;
    display: flex;
    gap: 10px;
}
</style>